using System;
using System.Collections.Generic;
using System.Text;

namespace Decav.Gatsb
{
    /// <summary>
    /// A validation code used to validate a users email or text message account.
    /// </summary>
    public struct UserValidationCode
    {
        public UserValidationCode(string str)
        {
            if (str == null)
                throw new ArgumentNullException("str");

            if (str.Length != 5)
                throw new ArgumentException("The validation code supplied is not 5 characters in length.");

            _value = str.ToUpper();
        }

        private string _value;

        /// <summary>
        /// The empty user validation code instance.
        /// </summary>
        public static readonly UserValidationCode Empty = new UserValidationCode();

        public override int GetHashCode()
        {
            if (_value == null)
                return 0;

            return _value.GetHashCode();
        }

        public override bool Equals(object obj)
        {
            if (obj == null)
                return false;

            if (obj.GetType() != typeof(UserValidationCode))
                return false;

            UserValidationCode code = (UserValidationCode)obj;

            return code._value == _value;
        }

        public override string ToString()
        {
            if (_value == null)
                return _value;

            return _value;
        }

        /// <summary>
        /// Generates a new unique user validation code.
        /// </summary>
        public static UserValidationCode Generate()
        {
            StringBuilder builder = new StringBuilder(5);
            
            for(int i =0; i<5; i++)
                builder.Append(_encodeChars[_rand.Next(0, _encodeChars.Length)]);

            return new UserValidationCode(builder.ToString());
        }

        private static Random _rand = new Random();
        private const string _encodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    }
}
